﻿var UserVm = function(jsonOfObject, allRoles) {
    var self = this;
    ko.mapping.fromJS(jsonOfObject, {}, self);
    self.UserRoles = ko.observableArray([]);


    self.IsInRole = function (roleId) {
        var userInRoleArray = ko.utils.arrayFilter(self.Roles(), function (role) {
            return (roleId == role.Id());
        });
        return userInRoleArray.length > 0;
    };

    self.InitUserRoles = function() {
        if (allRoles !== null) {
            var rolesArray = JSON.parse(allRoles);
            for (var i = 0; i < rolesArray.length; i++) {
                var role = new RoleVm(rolesArray[i]);
                var userRole = new UserRolesVm(self, role, self.IsInRole(role.Id()));
                self.UserRoles.push(userRole);
                }
            ko.utils.arrayForEach(self.UserRoles(), function(userRole) {
                userRole.IsUserInRole.subscribe(function(unused) {
                    var roleForUser = ko.utils.arrayFirst(self.Roles(), function(role) {
                        return role.Id() == userRole.Role.Id();
                    });
                    if (roleForUser == null) {
                        userRole.User.Roles.push(userRole.Role);
                    } else {
                        userRole.User.Roles.remove(roleForUser);
                    }
                });
            });
        };        
    }

    self.InitUserRoles();

};